# encoding=utf-8

import redis
import base64
import json

from seg_system import ApplicationConfig


class RedisService:
    redis_pool = redis.ConnectionPool(**ApplicationConfig.SystemConfig.REDIS_CONFIG)
    redis_conn = redis.Redis(connection_pool=redis_pool)

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_inst'):
            cls._inst = super(RedisService, cls).__new__(cls)
        return cls._inst

    @staticmethod
    def make_redis_key(u, t):
        return base64.b64encode((u + t).encode('utf-8')).decode()

    def make_dict(self, d: dict, key_list: list, value_list: list):
        for key, value in zip(key_list, value_list):
            if key not in d:
                d[key] = [value]
            else:
                d[key].append(value)
        return d

    def message_upload(self, key: str, value: dict):
        redis_value = json.dumps(value)
        RedisService.redis_conn.set(key, redis_value)

    def key_set(self, redis_key: str, key: str, value: str, **kwargs):
        """Redis只能存储基础数据类型，不能传递别的数据
        """
        res_d = self.key_get(redis_key)
        res_d[key] = value
        self.message_upload(redis_key, res_d)
        return redis_key

    def key_set_dict(self, redis_key: str, key_value_dict: dict, **kwargs):
        self.message_upload(redis_key, key_value_dict)
        return redis_key

    def key_get(self, redis_key: str):
        res = RedisService.redis_conn.get(redis_key)
        res = json.loads(res) if res else dict()
        return res

    def key_append(self, redis_key: str, key_list: list, value_list: list, **kwargs):
        res_d = self.key_get(redis_key)
        res_d = self.make_dict(res_d, key_list, value_list)
        self.message_upload(redis_key, res_d)
        return redis_key

    def key_remove(self, redis_key: str):
        return RedisService.redis_conn.delete(redis_key)
